/**
 * @method getMicroAppHashModeRoutes
 * @description 在子应用工程环境下 子应用路由自动添加应用名称前缀方法
 * @param routes
 * @param appName
 * @param microAppContainer
 * */
import {IMicroApp} from "../../types";

export const getMicroAppHashModeRoutes = (routes: any[] = [], appName: string, microAppContainer: any = null) => {
    if(!routes || !Array.isArray(routes)) return;
    if(Array.isArray(routes) && !routes.length) return;
    let prefix = "/";
    prefix = `/${appName}`;
    // 添加前缀
    routes.forEach((route) => {
        if (!route.component) {
            route.component = microAppContainer;
        }
        // 根路由
        if (route.path === "/") {
            route.path = prefix;
        } else {
            if (!route.path.includes(appName)) route.path = `${prefix}${route.path}`;
        }
        // redirect
        if (route.redirect && !String(route.redirect).includes(appName)) {
            route.redirect = `${prefix}${route.redirect}`;
        }
        // 子路由
        if (route.children) {
            getMicroAppHashModeRoutes(route.children, appName, microAppContainer);
        }
    });
    return routes;
};

/**
 * @method getMicroAppRoutesByRouteMode
 * @desc 在子应用工程环境下 根据当前路由模式重新计算子应用路由
 * @param routes
 * @param appName
 * @param routeMode
 * @param microAppContainer
 * */
export const getMicroAppRoutesByRouteMode = (
    routes = [],
    appName = "",
    routeMode = "hash",
    microAppContainer: any = null
) => {
    let microAppRoutes: any = routes;
    if (Array.isArray(routes) && routeMode === "hash" && appName) {
        microAppRoutes = getMicroAppHashModeRoutes(microAppRoutes, appName, microAppContainer);
    }
    return microAppRoutes;
};

export const MicroApp: IMicroApp = {
    getMicroAppHashModeRoutes,
    getMicroAppRoutesByRouteMode
}
